﻿using UnityEngine;

namespace XFramework
{

    public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
    {
        private static T _instance;

        public static T GetInstance()
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<T>();
                if (FindObjectsOfType<T>().Length > 1)
                {
                    Debug.LogError("不应该存在多个单例！");
                    return _instance;
                }

                if (_instance == null)
                {
                    var singleton = new GameObject();
                    _instance = singleton.AddComponent<T>();
                    singleton.name = "(singleton)" + typeof(T).Name;
                    DontDestroyOnLoad(singleton);
                }
                else
                    DontDestroyOnLoad(_instance.gameObject);
            }

            return _instance;
        }
    }
}